package com.ogawa.base.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;

import com.example.reslib.utils.PreferenceWrapper;
import com.ogawa.base.Constant.BleConstant;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by FHB on 2018/4/12.
 */
public class CommonUtil {
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static boolean isNetworkOnline() {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process ipProcess = runtime.exec("ping -c 3 www.baidu.com");
            int exitValue = ipProcess.waitFor();
            Log.i("Avalible", "Process:" + exitValue);
            return (exitValue == 0);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断某activity是否处于栈顶
     *
     * @return true在栈顶 false不在栈顶
     */
    public static boolean isActivityTop(Class cls, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(cls.getName());
    }

    public static String ActivityTop(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getShortClassName();
        return name;
    }

    public static boolean isOpera(String data) {
        return data.equals("1");
    }


    private static long lastClickTime;

    /**
     * 防止过快点击
     *
     * @return public void onClick(View v) {
     * if (CommonUtil.isFastClick()) {
     * return ;
     * }
     * else{}
     * }
     */
    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 防止过快点击
     *
     * @return public void onClick(View v) {
     * if (CommonUtil.isFastClick()) {
     * return ;
     * }
     * else{}
     * }
     */
    public synchronized static boolean isFastClick(long mdelay) {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < mdelay) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 命令拼接规则
     *
     * @param content
     * @return
     */
    public static String toSingleCommand(String content) {
        String hexStr = HexUtils.addHexString(BleConstant.COMMAND_HEAD + content);
        String newHexStr = hexStr.substring(hexStr.length() - 2,
                hexStr.length());
        String hexString = BleConstant.COMMAND_HEAD + content + newHexStr;
        return hexString;
    }

    /**
     * 开启View闪烁效果
     */

    public static void startFlick(View view) {
        if (null == view) {
            return;
        }
        Animation alphaAnimation = new AlphaAnimation(1, 0);
        alphaAnimation.setDuration(2000);
        alphaAnimation.setInterpolator(new LinearInterpolator());
        alphaAnimation.setRepeatCount(Animation.INFINITE);
        alphaAnimation.setRepeatMode(Animation.REVERSE);
        view.startAnimation(alphaAnimation);

    }

    /**
     * 取消View闪烁效果
     */
    public static void stopFlick(View view) {
        if (null == view) {
            return;
        }
        view.clearAnimation();
    }

    /**
     * byte类型转二进制字符串的代码
     *
     * @param data
     * @return
     */
    public static String showByteToString(byte data) {
        return Integer.toBinaryString((data & 0xFF) + 0x100).substring(1);
    }

    public static void setMargins(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

    //
    public static String getApkPath(Context context, String fileName) {
        String filePath = null;
        if (CommonUtil.checkSDCard(context)) {
            int api = Build.VERSION.SDK_INT;
            if (api < 17) {
                filePath = Environment.getExternalStorageDirectory()
                        .getAbsolutePath();
            } else {
                filePath = "/sdcard";
            }
        } else {
            filePath = context.getFilesDir().getAbsolutePath();
        }
        if (!filePath.endsWith("/")) {
            filePath += "/";
        }
        File file = new File(filePath);
        if (!file.exists())
            file.mkdirs();
        filePath = filePath + fileName + ".apk";
        return filePath;
    }


    /**
     * 检查网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }

        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }

        return true;
    }

    public static void installApk(Context context, String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static boolean checkSDCard(Context context) {
        return Storage.externalStorageAvailable();
    }

    public static String getAutoName(String value) {
        PreferenceWrapper mSp = new PreferenceWrapper();
        int mChoose = Integer.parseInt(mSp.getStringValue("app", "1"));
        String name = "";
        if (value.equals("1")) {
            name = "全身舒展";
        } else if (value.equals("2")) {
            name = "老年模式";
        } else if (value.equals("3")) {
            name = "泰式拉伸";
        } else if (value.equals("4")) {
            name = "速按放松";
        } else if (value.equals("5")) {
            name = "清晨唤醒";
        } else if (value.equals("6")) {
            name = "舒眠模式";
        } else if (value.equals("7")) {
            name = "运动恢复";
        } else if (value.equals("8")) {
            name = "深度放松";
        } else if (value.equals("9")) {
            name = "上班族";
        } else if (value.equals("10")) {
            name = "低头族";
        } else if (value.equals("11")) {
            name = mChoose == 4 ? "驾车族" : "开车族";
        } else if (value.equals("12")) {
            name = "高跟族";
        } else if (value.equals("13")) {
            name = "午间小休";
        } else if (value.equals("14")) {
            name = "女王美体";
        } else if (value.equals("15")) {
            name = "男士健体";
        } else if (value.equals("16")) {
            name = "久坐释压";
        } else if (value.equals("17")) {
            name = "酸痛检测";
        } else if (value.equals("18")) {
            name = "肩颈呵护";
        } else if (value.equals("19")) {
            name = "脊柱放松";
        } else if (value.equals("20")) {
            name = "腰臀养护";
        } else if (value.equals("21")) {
            name = "纤腿健足";
        }


        return name;

    }

    // 网络请求中文会被自动转成utf-8编码的格式类似%E5%93%88%E5%93%88  因此在签名url时也要转成同样格式
    public static String stringToUTF(String keyword) {
        String mkey = keyword;
        try {
            // 将application/x-www-from-urlencoded字符串转换成普通字符串
//            keyWord = URLDecoder.decode("%E5%93%88%E5%93%88", "UTF-8");
            Log.e("MainActivity", mkey + "");
            // 将普通字符创转换成application/x-www-from-urlencoded字符串
            mkey = URLEncoder.encode(keyword, "UTF-8");  //输出%C4%E3%BA%C3
            Log.e("MainActivity", mkey + "");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mkey;
    }

    public static String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    /**
     * 获取当前软件版本号
     *
     * @param context
     * @return
     * @author xxj
     * @time 2012-2-28 | 下午02:13:52
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionCode = pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return versionCode;
    }

    //状态栏高度
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static long recordAvailableSpace(Context context) {
        String filePath = null;
        if (CommonUtil.checkSDCard(context)) {
            int api = android.os.Build.VERSION.SDK_INT;
            if (api < 17) {
                filePath = Environment.getExternalStorageDirectory()
                        .getAbsolutePath();
            } else {
                filePath = "/sdcard";
            }
            StatFs stat = new StatFs(filePath);
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return availableBlocks * blockSize;
        }
        return -1;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPenGPS(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }



    //获取网络启动
    public static boolean getNetWorkStart(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                //连接服务 CONNECTIVITY_SERVICE
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        //网络信息 NetworkInfo
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
            //判断是否是wifi
            if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                //返回无线网络
                //  Toast.makeText(context, "当前处于无线网络", Toast.LENGTH_SHORT).show();
                return true;
                //判断是否移动网络
            } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                //  Toast.makeText(context, "当前处于移动网络", Toast.LENGTH_SHORT).show();
                //返回移动网络
                return true;
            }
        } else {
            //没有网络
            //  Toast.makeText(context, "当前没有网络", Toast.LENGTH_SHORT).show();
            return false;
        }
        //默认返回  没有网络
        return false;
    }

}
